package com.liuwei.msmall.order.interceptor;

import com.liuwei.msmall.common.constant.AuthServiceConstant;
import com.liuwei.msmall.common.dto.MemberRespDTO;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Classname OrderInterceptor
 * @Description TODO
 * @Date 2020/7/7 16:28
 * @Created by 刘
 */
@Component
public class OrderInterceptor implements HandlerInterceptor{

    //创建一个线程共享数据
    public static final ThreadLocal<MemberRespDTO> loginUserLocal=new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //对一些其他微服务需要调用的地址进行放行,如
        // 库存服务查询订单
        String uri = request.getRequestURI();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        //放行其他微服务调用路劲
        boolean match = antPathMatcher.match("/order/order/get/**", uri);
        //放行支付宝异步通知路径
        boolean match1 = antPathMatcher.match("/payed/notify", uri);
        if (match || match1){
            return true;
        }

        HttpSession session = request.getSession();
        MemberRespDTO user = (MemberRespDTO) session.getAttribute(AuthServiceConstant.LONGIN_USER);
        if (user!=null){
            //将用户的数据放在线程共享数据中
            loginUserLocal.set(user);
            //登录之后就放行
            return true;
        }

        //没登陆就,回到登录页登录
        session.setAttribute("nologinMsg","请先登录");
        response.sendRedirect("http://auth.msmall.com/login.html");
        return false;
    }
}
